﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using QWeiBoN.ViewModule;
using System.Collections.Generic;
using TencentWeiboSDK.Model;
using Microsoft.Phone.Tasks;
using System.Text.RegularExpressions;

namespace QWeiBoN.Converter
{
    /// <summary>
    /// 用于处理微博详情的内容
    /// </summary>
    public class ConvertWeiboDetailContent : Behavior<RichTextBox>
    {

        public static DependencyProperty ContentProperty = DependencyProperty.RegisterAttached("Content", typeof(string), typeof(RichTextBox), new PropertyMetadata(null, OnContentChanged));

        private UserListModel uModel = new UserListModel();

        public string Content
        {
            set
            {
                SetValue(ContentProperty, value);
            }
            get
            {
                return (string)GetValue(ContentProperty);
            }
        }

        public bool IsEnable { get; set; }

        private ICollection<User> userInfos { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public ConvertWeiboDetailContent()
        {
            IsEnable = true;
        }

        private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            string content = e.NewValue as string;
            ConvertWeiboDetailContent sender = d as ConvertWeiboDetailContent;
            if (!string.IsNullOrWhiteSpace(content) && d != null)
            {
                //sender.ConvertFanfouContent(content);
                sender.getUsersFromStatuContent(content);
                //sender.ConvertNewContent(content);
            }
        }

        /// <summary>
        /// 内容处理
        /// </summary>
        /// <param name="content"></param>
        void ConvertFanfouContent(string content)
        {
            int count = this.AssociatedObject.Blocks.Count;
            if (count < 1)
            {
                //getUsersFromStatuContent(content);
                //ConvertNewContent(content);
            }
        }

        void ConvertNewContent(string content)
        {
            // 新的内容处理方式
            var reg = @"@([A-Za-z0-9-_]*)?|\#([^\#|.]+)\#|http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?|/(no|ok|NO|OK|乒乓|亲亲|便便|偷笑|傲慢|再见|冷汗|凋谢|刀|勾引|发呆|发怒|发抖|可怜|可爱|右哼哼|右太极|吐|吓|咒骂|咖啡|哈欠|啤酒|嘘|回头|困|坏笑|大兵|大哭|太阳|奋斗|委屈|害羞|尴尬|左哼哼|左太极|差劲|弱|强|得意|微笑|心碎|快哭了|怄火|惊恐|惊讶|憨笑|抓狂|折磨|抠鼻|抱拳|拥抱|拳头|挥手|握手|撇嘴|擦汗|敲打|晕|月亮|流汗|流泪|激动|炸弹|爱你|爱心|爱情|猪头|献吻|玫瑰|瓢虫|疑问|白眼|睡|磕头|示爱|礼物|篮球|糗大了|胜利|色|菜刀|蛋糕|街舞|衰|西瓜|调皮|足球|跳绳|跳跳|转圈|鄙视|酷|闪电|闭嘴|阴险|难过|飞吻|饥饿|饭|骷髅|鼓掌|呲牙)";
            var regAccount = new Regex(reg);
            var matches = regAccount.Matches(content);
            int lastPos = 0;
            Paragraph block = new Paragraph();
            foreach (Match match in matches)
            {
                if (match.Index != lastPos)
                {
                    block.Inlines.Add(TextRun(content.Substring(lastPos, match.Index - lastPos)));
                }
                var val = match.Value;
                if (!string.IsNullOrWhiteSpace(val))
                {
                    if (val.IndexOf("@") == 0)
                    {
                        var run = new Run { Text = GetUserNickName(val.Substring(1)) };
                        //block.Inlines.Add(val);
                    }
                    else if (val.IndexOf("#") == 0)
                    {
                        //var run = new Run { Text = val };
                        var run = new Run { Foreground = (SolidColorBrush)App.Current.Resources["DetailComponentBrush"], Text = val };
                        block.Inlines.Add(run);
                    }
                    else if (val.IndexOf("/") == 0)
                    {
                        var img = BindFaceImage(val.Substring(1).ToLower());
                        if (img != null)
                        {
                            block.Inlines.Add(img);
                        }
                        else
                        {
                            block.Inlines.Add(val);
                        }
                    }
                    else
                    {
                        var link = new Hyperlink
                        {
                            NavigateUri = new Uri(val, UriKind.Absolute),
                            Foreground = (SolidColorBrush)App.Current.Resources["DetailComponentBrush"]
                        };
                        link.Inlines.Add(val);
                        link.Click += HyperlinkClick;
                        block.Inlines.Add(link);
                    }

                    lastPos = match.Index + match.Length;
                }
            }
            if (lastPos < content.Length)
            {
                block.Inlines.Add(TextRun(content.Substring(lastPos)));
            }

            // 测试添加图片
            //Image ImageControl = new Image();
            //String imageSource = "Resource/face/偷笑.png"; //获取表情uri
            //ImageControl.Source = new BitmapImage(new Uri(imageSource, UriKind.Absolute));
            //ImageControl.Stretch = Stretch.Fill;
            //ImageControl.Width = 21;
            //ImageControl.Height = 21;


            //InlineUIContainer imgUi = new InlineUIContainer();
            //imgUi.Child = ImageControl;
            //block.Inlines.Add(imgUi);

            // 测试加入gif图片
            //ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
            //ImageTools.ExtendedImage imgt = new ImageTools.ExtendedImage();
            //imgt.UriSource = new Uri("/Resource/face/偷笑.gif", UriKind.Relative);
            //AnimatedImage face = new AnimatedImage();
            //face.Source = (ImageTools.ExtendedImage)imgt;
            //var uiContainer = new InlineUIContainer();
            //uiContainer.Child = face;
            //block.Inlines.Add(uiContainer);

            this.AssociatedObject.Blocks.Clear();
            this.AssociatedObject.Blocks.Add(block);
        }

        /// <summary>
        /// 得到content中的用户
        /// </summary>
        /// <param name="Id"></param>
        void getUsersFromStatuContent(string content)
        {
            var contentHelper = new Util.StatusUtil();
            var accounts = contentHelper.MatchString(content, Util.StatusUtil.AccountReg);
            if (accounts.Count > 0)
            {
                var tmpAccounts = new List<string>();
                foreach (var n in accounts)
                {
                    var name = n.Substring(1);
                    if (!tmpAccounts.Contains(name))
                    {
                        tmpAccounts.Add(name);
                    }
                }
                uModel.getUserFromUserIds(tmpAccounts, (users) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        userInfos = users;
                        //ConvertFanfouContent(content);
                        ConvertNewContent(content);
                    });
                });
            }
            else
            {
                userInfos = null;
                Dispatcher.BeginInvoke(() =>
                {
                    userInfos = null;
                    //ConvertFanfouContent(content);
                    ConvertNewContent(content);
                });
            }
        }

        /// <summary>
        /// 用于清理字符串
        /// </summary>
        /// <param name="sourceStrs"></param>
        /// <returns></returns>
        List<string> clearStrs(string[] sourceStrs)
        {
            List<string> list = new List<string>();
            for (int i = 0; i < sourceStrs.Length; i++)
            {
                if (sourceStrs[i].Trim().Equals(""))
                {
                    break;
                }
                else
                {
                    list.Add(sourceStrs[i].Trim());
                }
            }
            return list;
        }

        private Run TextRun(string text)
        {
            return new Run
            {
                Foreground = new SolidColorBrush((Color)App.Current.Resources["DetailContentColor"]),
                Text = text,
                FontFamily = new FontFamily("Microsoft YaHei")
            };
        }

        /// <summary>
        /// 生成表情图片
        /// </summary>
        /// <param name="faceName"></param>
        /// <returns></returns>
        private InlineUIContainer BindFaceImage(string faceName)
        {

            if (Util.FaceUtil.Exist(faceName))
            {
                var uri = new Uri(Util.FaceUtil.GetFaceUrl(faceName), UriKind.Relative);
                //ImageTools.ExtendedImage imgt = new ImageTools.ExtendedImage();
                //imgt.UriSource = uri;
                //var face = new AnimatedImage();
                //face.Source = imgt;
                var face = new Image
                {
                    Source = new System.Windows.Media.Imaging.BitmapImage(uri),
                    Stretch = Stretch.Fill,
                    Width = 24,
                    Height = 24,
                    Margin = new Thickness(0, 0, 0, 0)
                };
                var uiContainer = new InlineUIContainer();
                uiContainer.Child = face;
                return uiContainer;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 打开网页
        /// </summary>
        private void HyperlinkClick(object sender, RoutedEventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    var link = sender as Hyperlink;
                    var webBrowserTask = new WebBrowserTask
                    {
                        Uri = new Uri(link.NavigateUri.AbsoluteUri, UriKind.Absolute)
                    };
                    webBrowserTask.Show();
                });
            }
            catch
            {

            }
        }

        /// <summary>
        /// 用户名称的处理
        /// </summary>
        /// <param name="name"></param>
        /// <param name="users"></param>
        /// <returns></returns>
        private string GetUserNickName(string name)
        {
            var rs = name;
            if (userInfos != null)
            {
                foreach (var u in userInfos)
                {
                    if (string.Compare(name, u.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        return u.Nick;
                    }
                }
            }
            return "@" + rs;
        }

        //获取文本的宽度
        private double GetContentWidth(String aSrc)
        {
            TextBlock text = new TextBlock();
            //text.FontSize = contentFontSize;
            text.Text = aSrc;
            return text.ActualWidth;
        }
    }
}
